from django.core.paginator import Paginator
from django.forms import model_to_dict
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from entity.common.response import ResponseData, ResponseStatus
from goodsApp.goodsModel.models import Goods
from utils.transfer import transferToJson

def getGoodsByPage(request):
    """全部商品页面"""
    cur = request.GET.get('page',1)
    size = request.GET.get('size',5)
    goods = Goods.objects.all()
    page_obj = Paginator(goods, size)
    glist = page_obj.get_page(cur).object_list
    result = []
    for g in glist:
        result.append(model_to_dict(g,exclude=["description","storage","href","categoryId"]))
    response = ResponseData(success=False,responseCode=ResponseStatus.SUCESS,data=result)
    return HttpResponse(content=transferToJson(response), content_type=ResponseData.JSON_CONTENT_TYPE)


def goodsDetail(request):
    """商品详情页面"""
    goodsId = request.GET.get('id')
    goodsInfo = Goods.objects.get(id=goodsId)
    return render(request=request,template_name="detail.html",context=goodsInfo.__dict__)

def goodsSearch(request):
    keyword = request.session['keyword']
    cur = request.GET.get('page',1)
    size = request.GET.get('size',5)
    gl = Goods.objects.values('img','price','id','title').filter(description__icontains=keyword)
    page_obj = Paginator(gl, size)
    goods_list = []
    for g in page_obj.get_page(cur).object_list:
        goods_list.append(g)
    return JsonResponse(goods_list,safe=False)
